  function ocell = out_ctdraws(mat,oname,in); 
% function ocell = out_ctdraws(mat,oname,into);
%
% TABLES FOR T X C MATRICES with DRAWS 
% =====================================
%
% This code creates tables and graphs for an input matrix
% mat of dimension [ T   nc    ndr ] 
% where T       time vector 
%            nc     number of columns 
%            ndr    number of draws 
% i.e. use with the output of  time varying parameters,
% states or factors 
% 
% Inputs 
% =====
% mat         matrix
% oname       filename (required) for the table/cell
% 
%
% Structure in allows for all other options, default values in parenthesis 
% =========================================================================
% 
% in.cnames = { 'TRY'  }; 
% in.colplot =  1    ; 
% in.rowplot =  1   ; 
% in.title   =   'THIS'   ; 
% in.gname   = 
% in.cvec    =      ; 


% in.perc       percentiles (<0.5) for the draws 
%                    1-in.perc  computed inside the code 
%                    ( [0.05 0.16] ) 
%
% in.plotperc   percentile (position in in.perc) to use in the plots 
%                   ( 1 , ie. 0.05 and 0.95 ) 
%
% in.cnames     columns names, cell with dimension C 
%                  ( [col1 col2 ....colC] )
%
% in.colplot    Plots will be divided into row x plots per page , this defines number of columns
%                        ( 2 ) 
%
% in.rowplot    Plots will be divided into row x plots per page , this defines number of row 
%                        (2 )
%
% in.axfont     Axis fontsize, ( 6 ) 
%
% in.title      First part of the title for the graphs 
%                  title for ii-th graph  will be [ in.title in.cnames(ii) ] 
%                  ( series ) 
%
%in.topcell     Column cell with unlimited number of 
%                   entries will be placed in column 1 for the first rows of the table
%                   ( Table ) 
%
%in.gname       Names for saving the graphs 
%                Graphs will be saved as in.gname_<number> 
%                 ( g_ctdraws ) 
%
% in.cvec       Calendar vector of dimension T x 1 
%               ( [1:T] ) 
%
% % in.ylim       Limits for the y-axis 
%               Four possibilities. 
%               1) Dimension 2x1 and (1,1) different (2,1) 
%                  then (1,1) Lower Bound ; (2,1) Upper Bound
%
%               2) Dimension 2x1 and (1,1)==(2,1) 
%                  then single number is a percent to add and substract \
%                  from above and below 
%
%               3) Dimension 2 x 2, first column different elements
%                  [   substract from min   Lower Bound; 
%                      add       from max   Upper Bound ]
%                  ( [], axis tight ) 
%
%
%               4) Dimension 2 x 2, first column == elements
%                  [   substract %from min   Lower Bound; 
%                      add same  %from max   Upper Bound ]
%                  ( [], axis tight ) 
%
% Alejandro Justiniano 5/1/2005 
% Modified 5/4/2005     Use rows and columns option, legend only first graph
%          5/15/2005    in.ylim as an option 
%          10/24/2005    Accept 2 dimensional matrices, transform into a 
%                       [ t 1 c] and set rowplot and colplot to 1 
% 
%  
% Note: correct the plotperc option having changed pmat !
%
% =============================================
% Use following code to ensure elements ordered appropriately 
% mu=[1:4]; 
% SDX=diag( linspace( 0.1 , 1 , 4 ) ); 
% draws=mvnrnd( mu, SDX , 10 ); 
% mat=zeros(10,4,200); 
% hh=1; 
% for hh=1:200; 
%     dr1 =mvnrnd( mu, SDX , 5 ); 
%     dr2 =mvnrnd( mu, 3*SDX , 5 ); 
%     mat(1:5,:,hh) = dr1; 
%     mat(6:end,:,hh) = dr2;
% end
% 


cucd=cd; 
dim=size(mat); 


if nargin < 3
    in.npg  = 3;
else
    if isstruct( in ) == 0
        error('Input in must be a structure')
    end
end

flag_save = 1; 
if nargin < 2 | isempty( oname ) == 1 | isstr(oname) == 0 
    flag_save = 0;
end 

if length( dim ) ~= 3
    if length( dim ) == 2
        mat = reshape( mat , [ dim(1) 1 dim(2) ] );
        dim=[dim(1) 1 dim(2)];
    else
        error('Input must be a 3d matrix')
    end
end 

    
T=dim(1); 
nc=dim(2); 
ndr=dim(3); 
% if ndr < T | ndr < nc 
%     error('Pages must store draws') 
% end 



% Check fields and assign default values otherwise 
% -------------------------------------------------
[e,in]=ch_field( in ,'perc', [0.05 0.16] );
if nc ~= 1
    [e1,in]=ch_field( in, 'colplot', 2 );
    [e2,in]=ch_field( in, 'rowplot', 2 );
    if e1 == 1 | e2 == 1
        if e1 == 0
            error('Structure in must define in.colplot or leave in.rowplot empty')
        end
        if e2 == 0
            error('Structure in must define in.rowplot or leave in.colplot empty')
        end
    end
    clear e1 e2;
else
    in.colplot = 1;
    in.rowplot = 1;
end

[e2,in]=ch_field(in, 'axfont', 7 );
[e,in]=ch_field( in, 'plotperc', 1 ); 
[e,in]=ch_field( in, 'cnames' ); 
if e==0 
    in.cnames = fnumcell('col ',[1:nc] ); 
end 
[e,in]=ch_field( in, 'e' ,'Series' ); 
[e,in]=ch_field( in, 'topcell', {'Table'} ); 
[e,in]=ch_field( in, 'gname' , 'g_ctdraws') ; 
[e,in]=ch_field( in, 'outpath', cucd ); 
[e,in]=ch_field( in, 'cvec', 1:T ); 

% ===========================
% Vector of limist for y-axis 
% ===========================
[e,in]=ch_field( in, 'ylim' );
if e==0
    flag_ylim = 0 ;
else
    mins = min( size(in.ylim) );
    if mins > 2
        error('in.ylim must be of dimension [2 1] or [2 2]' )
    end
    flag_ylim = 1; 
    flag_perc = ( ( in.ylim(1) - in.ylim(2) ) == 0 ) ; 
    caseind = flag_perc*mins + (1-flag_perc)*(mins-1) + mins; 
    clear mins flag_perc    
end

set(0,'DefaultAxesFontSize',in.axfont);

if length( in.cvec ) ~= T 
    error('Input in.calvec must be of the same size as rows of mat'); 
end
perc=(sort(in.perc(:)) )';
temp = find( perc > 0.49 ); 
if ~isempty( temp ) 
    perc(temp) = [] ; 
end 
perc2 = 1-perc; 
pmat=[perc;perc2]; 
clear perc*; 
pmat=pmat(:); 
pcell=num2cprec( 100*pmat )'; 
exind = round( ndr*pmat ); 

ppercind = [2*(in.plotperc-1) + 1  2*in.plotperc] ; 


% Header Cell
head2={'Mean','Median','Std'}; 
head2=[head2 pcell]; 
clear pmat; 

% ===========================
% Cell dimension nrow x ncol 
% ===========================
ncell=length( in.topcell ); 
ntop = max( ncell , 3 ) + 1; 
np=length( exind ); 
ndiv = 3+np; 
ncol=nc*ndiv + 1; 
nrow=T+ntop; 

% Position indicators 
posmat =2:ncol; 
posmat=reshape( posmat , ndiv , nc ); 


ocell=emptycell( nrow, ncol ); 
ocell(1:ncell,1) = in.topcell ; 
clear ncell; 
ocell(ntop+1:end,1) = num2cprec( in.cvec(:) ); 
ocell(ntop,1) ={'Date'}; 

ocell(ntop,2:end) = fillcell(1,ncol-1,'=======' ); 

ipg=0; 
countg=0; 

npg = in.colplot*in.rowplot ; 

hh=1; 
for hh=1:nc; 
    
    % Series Specific Entries 
    ocell(ntop-2,posmat(:,hh) ) = repmat( in.cnames(hh) ,1 ,  ndiv ) ;
    ocell( ntop-1 ,posmat(:,hh) ) = head2; 
    
    tempx=squeeze(mat(:,hh,:)); 
    temp_med = real( median( tempx , 2) ); 
    temp_mean = real( mean( tempx , 2) );  
    ocell(ntop+1:end,posmat(1:2,hh) ) =num2cprec(  [temp_mean temp_med ] , 3 );   
    ocell(ntop+1:end,posmat(3,hh)  ) =num2cprec(  std(tempx')' , 3 ); 
    temp_perc = tempx(:,exind ); 
    tempx=sort(tempx,2); 
    ocell(ntop+1:end,posmat(4:end,hh) ) = num2cprec( tempx(:,exind) , 4 ) ; 
    
    if flag_save == 1
        savecell( ocell, cucd, in.outpath , oname );
    end
    %printcell( ocell );

    
    % Create plots 
    if ipg == 0 
        figure; 
    end 
    ipg = ipg + 1; 
    
    subplot(in.rowplot, in.colplot , ipg ); 
    hold; 
    plot( in.cvec , temp_med , '-b' ); 
    plot( in.cvec , temp_mean, '-k','LineWidth',1.5 ); 
    plot( in.cvec , tempx(:,exind(ppercind(1)) ),':r' ); 
    plot( in.cvec , tempx(:,exind(ppercind(2)) ),':r' );
    hold off; 
    axis tight; 
    
    title( [in.title,'  ',in.cnames{hh}],'FontSize',8 ); 
    
    if ipg == 1 
        lh=legend('Mean','Median',pcell{ppercind(1)},pcell{ppercind(2)},0 ); 
        set(lh,'FontSize',6,'FontWeight','Bold');
    end 

    
    if flag_ylim == 1
        temp_min = min( min( tempx(:,exind(ppercind(1)) ) ) );
        temp_max = max( max( tempx(:,exind(ppercind(2)) ) ) );
         switch caseind

            case 1
                ylim( [temp_min-in.ylim(1)  temp_max+in.ylim(2)] );
            case 2
                ylim( [ temp_min*(1-in.ylim(1)) temp_max*(1+in.ylim(1)) ] );
            case 3
                temp_min = max( [temp_min-in.ylim(1,1) ; in.ylim(1,2) ] );
                temp_max = min( [temp_max+in.ylim(2,1) ; in.ylim(2,2) ] );
                 ylim( [temp_min temp_max] );
            case 4
                temp_min = max( [temp_min - in.ylim(1,1) ; in.ylim(1,2) ] );
                temp_max = min( [temp_max + in.ylim(2,1) ; in.ylim(2,2) ] );
                ylim( [temp_min temp_max] );
        end
    end
    
    if ipg == npg | hh==nc 
        
        countg = countg + 1; 
        ipg =0;
        cd( in.outpath ); 
        saveas( gcf , [in.gname,'_',num2str(countg)] , 'fig' );
        print(gcf,'-deps',[in.gname,'_',num2str(countg)] );
        cd( cucd ); 
        
    end
 
end 


set(0,'DefaultAxesFontSize','remove');